// pages/home/home.js
import {$http, formatTime} from './../../utils/util';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    success: false,
    plateNumber: null,
    appointments: [],
    binded: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let binded = wx.getStorageSync('binded');
    if (binded) {
      // 1.加载用户今天已经预约的信息
      this.loadPlateNumber(); 
    }
    this.setData({
      binded
    })
  },
  onShow: function() {
    // 1.加载用户今天已经预约的信息
    if (this.data.binded) {
      this.loadCurrentAppointment(); 
    }
  },
  /**
   * 加载手机号
   */
  loadPlateNumber() {
    this.setData({
      plateNumber: wx.getStorage({
        key: 'plateNumber',
        success: res => this.setData({
          plateNumber: res.data
        })
      })
    })
  },
  /**
   * 加载用户今天已经预约的信息
   */
  loadCurrentAppointment() {
    $http.get({
      url: '/getCurrentAppointment',
      success: res => {
        if (res.data.code === 200) {
          let appointments = res.data.data;
          if (appointments) {
            appointments.map(item => {
              item.startDate = formatTime(new Date(item.startDate));
              item.endDate = formatTime(new Date(item.endDate));
              item.createDate = formatTime(new Date(item.createDate));
              return item;
            })
          }
          this.setData({
            success: true,
            appointments
          });
          wx.setStorageSync('appointments', appointments);
        } else {
          this.setData({
            success: false,
            appointments: null
          });
          wx.removeStorageSync('appointments');
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络出错',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },

  /**
   * 跳转到预约界面
   */
  onBindToAppoint() {
    wx.navigateTo({
      url: '/pages/appoint/select/select',
    })
  },
  /**
   * 跳转到历史界面
   */
  onBindToHistory() {
    wx.switchTab({
      url: '/pages/history/history',
    })
  },
  /**
   * 跳转到查看预约单详情的界面
   */
  onClickToDetail(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/appoint/my/my?id=' + id,
    })
  }
})